﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using GMAC.ReportingSystem.Business.Entities;
using FrameworkManapro.BusinessModel;
using Excel = Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using GMAC.ReportingSystem.Business.Entities.Configuration;
using FrameworkManapro.WebUI;

namespace GMAC.ReportingSystem.Business.Components
{
    public class AdditionalInformationDealerComponent : IBusinessComponent<StringAdditionalInformationDealer>
    {

        // Referencia la clase de datos
        private DataAccess.AdditionalInformationDealerDataAccess dac;

        // Constructor que instancia la capa de datos
        #region Constructor
            /// <summary>
            /// Constructor de la la clase de negocios que crea una instancia de la clase de datos
            /// </summary>
            public AdditionalInformationDealerComponent()
            {
                dac = new DataAccess.AdditionalInformationDealerDataAccess();
            } // ASLTelecomComponent
        #endregion


        // Metodos no Implementados pide que pide "IBusinessComponent"
        #region IBusinessComponent<StringAdditionalInformationDealer> Members

        /// <summary>
        /// Metodo no implementado
        /// </summary>
        /// <param name="entityToCreate"></param>
        /// <returns></returns>
        public int Create(StringAdditionalInformationDealer entityToCreate)
        {
            throw new NotImplementedException();
        } // Create

        /// <summary>
        /// Metodo no implementado
        /// </summary>
        /// <param name="entityToDelete"></param>
        /// <returns></returns>
        public int Delete(StringAdditionalInformationDealer entityToDelete)
        {
            throw new NotImplementedException();
        } // Delete

        /// <summary>
        /// Metodo no implementado
        /// </summary>
        /// <param name="entityToEdit"></param>
        /// <returns></returns>
        public int Edit(StringAdditionalInformationDealer entityToEdit)
        {
            throw new NotImplementedException();
        } // Edit

        /// <summary>
        /// Metodo no implementado
        /// </summary>
        /// <param name="entityId"></param>
        /// <returns></returns>
        public StringAdditionalInformationDealer GetDetails(object entityId)
        {
            throw new NotImplementedException();
        } // GetDetails

        #endregion


        #region "Metodos"

        /// <summary>
        /// Carga el archivo "LAO SAlvage - Regional Extract" que contiene las cuentas con estatus PERDIDA
        /// </summary>
        /// <remarks>El archivo es de tipo Excel</remarks>
        /// <param name="processDate">Fecha en la que se esta procesando el archivo</param>
        /// <param name="fileName">Ruta y nombre del archivo a procesar</param>
        /// <param name="UserId">Usuari oquer ejecuta la operacion</param>
        /// <param name="LAOInvalids">Lista de los registros invalidos que se encontraron en el archivo</param>
        /// <param name="LAOValids">Lista de los registros validos que se encontraron en el archivo</param>
        public void LoadFile(DateTime processDate, string fileName, int userId, PagingDetails pagingSuccessful, PagingDetails pagingFailed, ref StringAdditionalInformationDealerCollection invalids, ref StringAdditionalInformationDealerCollection valids, out int totalRecordsSuccessful, out int totalRecordsFailed)
        {
            // Primera fila de los datos en el archivo
            int FIRST_ROW = 2;

            StringAdditionalInformationDealerCollection Records = new StringAdditionalInformationDealerCollection();

            //  asigna las columnas donde se encuentran los datos en el archivo excel
            string COL_1_ADDITIONALINFORMATIONDEALERNUMBER          = "A";
            string COL_2_ADDITIONALINFORMATIONDEALERMONTH           = "B";
            string COL_3_ADDITIONALINFORMATIONDEALERGMACACADEMY     = "C";
            string COL_4_ADDITIONALINFORMATIONDEALERTWITER          = "D";

            var oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
            System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
            var app = new Excel.Application();
            Excel.Workbook wb = null;
            var missing = Type.Missing;
            StringAdditionalInformationDealer Record;

            try
            {
                string strCulture = System.Configuration.ConfigurationManager.AppSettings["Culture"];
                System.Globalization.CultureInfo infCulture = new System.Globalization.CultureInfo(strCulture);

                wb = app.Workbooks.Open(fileName, missing, true, missing, missing,
                    missing, true, missing, missing, missing, false,
                    missing, false, true, false);
                var sheet = wb.Sheets[1] as Excel.Worksheet;
                if (sheet != null)
                {
                    int i = FIRST_ROW;

                    // Formatea las letras de las columnas en el excel de las que proviene los valores
                    var cell1_ADDITIONALINFORMATIONDEALERNUMBER         = string.Format("{0}{1}", COL_1_ADDITIONALINFORMATIONDEALERNUMBER, i);
                    var cell2_ADDITIONALINFORMATIONDEALERMONTH          = string.Format("{0}{1}", COL_2_ADDITIONALINFORMATIONDEALERMONTH, i);
                    var cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY    = string.Format("{0}{1}", COL_3_ADDITIONALINFORMATIONDEALERGMACACADEMY, i);
                    var cell4_ADDITIONALINFORMATIONDEALERTWITER         = string.Format("{0}{1}", COL_4_ADDITIONALINFORMATIONDEALERTWITER, i);                    

                    // declare las variables donde se capturaran los valores de cada filas del excel
                    string str_cell1_ADDITIONALINFORMATIONDEALERNUMBER      = sheet.get_Range(cell1_ADDITIONALINFORMATIONDEALERNUMBER       , cell1_ADDITIONALINFORMATIONDEALERNUMBER).Text.ToString().Trim();
                    string str_cell2_ADDITIONALINFORMATIONDEALERMONTH       = sheet.get_Range(cell2_ADDITIONALINFORMATIONDEALERMONTH        , cell2_ADDITIONALINFORMATIONDEALERMONTH).Text.ToString().Trim();
                    string str_cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY = sheet.get_Range(cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY  , cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY).Text.ToString().Trim();
                    string str_cell4_ADDITIONALINFORMATIONDEALERTWITER      = sheet.get_Range(cell4_ADDITIONALINFORMATIONDEALERTWITER       , cell4_ADDITIONALINFORMATIONDEALERTWITER).Text.ToString().Trim();
                    
                    // Se hara el while mientras exista por lo menos un campo con longitudes > 0
                    while (str_cell1_ADDITIONALINFORMATIONDEALERNUMBER.Length > 0
                           || str_cell2_ADDITIONALINFORMATIONDEALERMONTH.Length > 0
                           || str_cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY.Length > 0
                           || str_cell4_ADDITIONALINFORMATIONDEALERTWITER.Length > 0                           
                          ) // while
                    {
                        // Inicializa la cadena que captura las razones de rechazo
                        //strRejectionReason = "";

                        // Instancia los objetos para capturar una fila de el archivo e insertarlos en la coleccion de los validos o los invalidos
                        Record = new StringAdditionalInformationDealer();

                        Record.LoadDate = processDate;
                        Record.AdditionalInformationDealerNumber = str_cell1_ADDITIONALINFORMATIONDEALERNUMBER;
                        Record.AdditionalInformationDealerMonth = str_cell2_ADDITIONALINFORMATIONDEALERMONTH;
                        Record.AdditionalInformationDealerGMACAcademy = str_cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY;
                        Record.AdditionalInformationDealerTwiter = str_cell4_ADDITIONALINFORMATIONDEALERTWITER;

                        // Agrega el Item a la coleccion
                        Records.Add(Record);

                        // Se mueve al siguiente registro del while
                        i++;

                        // Formatea las letras de las columnas en el excel de las que proviene los valores
                        cell1_ADDITIONALINFORMATIONDEALERNUMBER = string.Format("{0}{1}", COL_1_ADDITIONALINFORMATIONDEALERNUMBER, i);
                        cell2_ADDITIONALINFORMATIONDEALERMONTH = string.Format("{0}{1}", COL_2_ADDITIONALINFORMATIONDEALERMONTH, i);
                        cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY = string.Format("{0}{1}", COL_3_ADDITIONALINFORMATIONDEALERGMACACADEMY, i);
                        cell4_ADDITIONALINFORMATIONDEALERTWITER = string.Format("{0}{1}", COL_4_ADDITIONALINFORMATIONDEALERTWITER, i);

                        // vuelve a capturar los valores de la siguiente fila del excel para el while
                        str_cell1_ADDITIONALINFORMATIONDEALERNUMBER = sheet.get_Range(cell1_ADDITIONALINFORMATIONDEALERNUMBER, cell1_ADDITIONALINFORMATIONDEALERNUMBER).Text.ToString().Trim();
                        str_cell2_ADDITIONALINFORMATIONDEALERMONTH = sheet.get_Range(cell2_ADDITIONALINFORMATIONDEALERMONTH, cell2_ADDITIONALINFORMATIONDEALERMONTH).Text.ToString().Trim();
                        str_cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY = sheet.get_Range(cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY, cell3_ADDITIONALINFORMATIONDEALERGMACACADEMY).Text.ToString().Trim();
                        str_cell4_ADDITIONALINFORMATIONDEALERTWITER = sheet.get_Range(cell4_ADDITIONALINFORMATIONDEALERTWITER, cell4_ADDITIONALINFORMATIONDEALERTWITER).Text.ToString().Trim();

                    } // while

                    // Asigna los parametros de pagineo
                    if (string.IsNullOrEmpty(pagingSuccessful.SortBy))
                        pagingSuccessful.SortBy = "AdditionalInformationDealerNumber";

                    if (pagingSuccessful.PageNumber <= 0)
                    {
                        pagingSuccessful.PageNumber = 1;
                        pagingSuccessful.PageSize = 10;
                    } // if (pagingSuccessful.PageNumber <= 0)

                    if (string.IsNullOrEmpty(pagingFailed.SortBy))
                        pagingFailed.SortBy = "AdditionalInformationDealerNumber";

                    if (pagingFailed.PageNumber <= 0)
                    {
                        pagingFailed.PageNumber = 1;
                        pagingFailed.PageSize = 10;
                    } // if (pagingFailed.PageNumber <= 0)
                        

                    dac.UploadLoanFile(processDate, userId, Records, pagingSuccessful, pagingFailed, ref invalids, ref valids, out totalRecordsSuccessful, out totalRecordsFailed);
                } // if (sheet != null)
                else
                {
                    throw new ApplicationException("File invalid.");
                }
            } // try
            catch
            {
                throw;
            } // catch
            finally
            {
                if (wb != null)
                {
                    wb.Close(false, missing, missing);
                    Marshal.FinalReleaseComObject(wb);
                } // if
                if (true)
                {
                    app.Quit();
                    Marshal.FinalReleaseComObject(app);
                } // if
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;

            } // finally
        } // LoadFile

        public StringAdditionalInformationDealerCollection GetAdditionalInformationDealers(LoadFileStatus status, DateTime processDate, int user, PagingDetails paging, out int totalRecords)
        {
            StringAdditionalInformationDealerCollection Records = dac.GetAdditionalInformationDealers(status, processDate, user, paging, out totalRecords);

            return Records;
        } // GetAdditionalInformationDealers


        /// <summary>
        /// Metodo que inserta los registros valios del archivo excel
        /// </summary>
        /// <param name="typeFile">Tipo de archivo</param>
        /// <param name="UserId">Usuario que procesa el archivo</param>
        public void GenerateUploadFile(int UserId)
        {
            dac.GenerateUploadFile(UserId);
        } // GenerateUploadFile

        /// <summary>
        /// Recibe una coleccion y la retorna ordenada segun indiquen los parametros
        /// </summary>
        /// <param name="records">Coleccion de valores a ordenar</param>
        /// <param name="column">Campo por el que va a ordenar</param>
        /// <param name="order">"ASC" o "DESC"</param>
        /// <returns>Lista ordenada</returns>
        public StringAdditionalInformationDealerCollection sord(StringAdditionalInformationDealerCollection records, string column, string order)
        {
            return dac.sord(records, column, order);
        } // sord


            /// <summary>
            /// Valida si los datos son numericos
            /// </summary>
            /// <param name="value">Valor a validar</param>
            /// <returns>
            /// true: Es Valido
            /// false: No es Valido
            /// </returns>
            public bool IsNumeric(string value)
            {
                try
                {
                    long.Parse(value);
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            } // IsNumeric

            /// <summary>
            /// Valida si los datos son Decimales
            /// </summary>
            /// <param name="value">Valor a validar</param>
            /// <returns>
            /// true: Es Valido
            /// false: No es Valido
            /// </returns>
            public bool IsDecimal(string value)
            {
                try
                {
                    decimal.Parse(value);
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            } // IsDecimal

            /// <summary>
            /// Valida si los datos son Date
            /// </summary>
            /// <param name="value">Valor a validar</param>
            /// <returns>
            /// true: Es Valido
            /// false: No es Valido
            /// </returns>
            public bool IsDate(string value)
            {
                try
                {
                    string strCulture = System.Configuration.ConfigurationManager.AppSettings["Culture"];

                    DateTime.Parse(value, new System.Globalization.CultureInfo(strCulture));

                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            } // IsDate

        #endregion


    } // class
} // namespace
